package com.travelSpring.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.travelSpring.annotation.RequireAdmin;
import com.travelSpring.common.Result;
import com.travelSpring.pojo.entity.User;
import com.travelSpring.service.UserService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * 功能：
 * 作者：卷心菜
 * 日期：2025/3/1 18:50
 */
@RestController
@RequestMapping("/user")
@RequireAdmin
public class UserController {

    @Resource
    UserService userService;


    @PostMapping("/query")
    public Result query(@RequestBody User user) {
        List<User> query = userService.selectAll(user);
        return Result.success(query);
    }

    @PostMapping("/addUser")
    public Result add(@RequestBody User user) {
        userService.add(user);
        return Result.success();
    }

    @PostMapping("/updateUser")
    public Result update(@RequestBody User user) {
        userService.update(user);
        return Result.success();
    }

    @PostMapping("/updateBatch")
    public Result updateUser(@RequestBody List<User> list) {
        userService.updateBatch(list);
        return Result.success();
    }

    @DeleteMapping("/deleteUser/{id}")
    public Result delete(@PathVariable Integer id) {
        userService.deleteById(id);
        return Result.success();
    }

    @DeleteMapping("/deleteBatch")
    public Result deleteBatch(@RequestBody List<User> list) {
        userService.deleteBatch(list);
        return Result.success();
    }

    @GetMapping("/selectAll")
    public Result selectAll(User user) {
        List<User> users = userService.selectAll(user);
        return Result.success(users);
    }

    @GetMapping("/selectPage")
    public Result selectPage(@RequestParam(defaultValue = "8") Integer pageSize,
                             @RequestParam(defaultValue = "1") Integer pageNum,
                             User user){
        IPage<User> userIPage = userService.selectPage(pageSize, pageNum, user);

        return Result.success(userIPage);
    }

    @PostMapping

    /**数据导出*/
   @GetMapping("/export")
    public void exportData(User user,HttpServletResponse response) throws Exception {
       String ids = user.getIds();
       List<User>lists =userService.selectBatchId(ids);
       if(lists.size()==0){
           lists = userService.selectList();
       }
       ExcelWriter writer = ExcelUtil.getWriter(true);
       writer.addHeaderAlias("username","账号");
       writer.addHeaderAlias("name","名称");
       writer.addHeaderAlias("phone","电话");
       writer.addHeaderAlias("email","邮箱");
       writer.addHeaderAlias("address","地址");
       writer.addHeaderAlias("role","身份");
       writer.setOnlyAlias(true);
       writer.write(lists);
       String fileName = URLEncoder.encode("管理员信息", "UTF-8");
       response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
       response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
       ServletOutputStream os = response.getOutputStream();
       writer.flush(os);
       os.flush();
       os.close();
   }

    @PostMapping("/import")
    public Result importData(@RequestParam("file") MultipartFile file) throws Exception {
        // 1. 检查文件是否为空
        if (file.isEmpty()) {
            return Result.error("上传文件不能为空");
        }
        // 2. 解析Excel
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        reader.addHeaderAlias("账号", "username");
        reader.addHeaderAlias("名称", "name");
        reader.addHeaderAlias("电话", "phone");
        reader.addHeaderAlias("邮箱", "email");
        reader.addHeaderAlias("地址", "address");
        reader.addHeaderAlias("身份", "role");

        List<User> users = reader.readAll(User.class);

        // 3. 检查解析结果
        if (users == null || users.isEmpty()) {
            return Result.error("Excel内容为空或格式错误");
        }
        // 4. 处理数据
        for (User user : users) {
            user.setId(null); // 显式设置ID为null，确保使用自增
            if (StringUtils.isEmpty(user.getUsername())) {  // 检查必要字段
                throw new IllegalArgumentException("用户账号不能为空");
            }
            userService.add(user); // 确保userService已注入
        }

        return Result.success();
    }


}


